package com.ruipeng.shengyapo.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import com.ruipeng.shengyapo.comm.ResponseData;
import com.ruipeng.shengyapo.dao.CouponMapper;
import com.ruipeng.shengyapo.dao.OrderMapper;
import com.ruipeng.shengyapo.dao.UserMapper;
import com.ruipeng.shengyapo.locksocket.LockManager;
import com.ruipeng.shengyapo.locksocket.NettyChannelMap;
import com.ruipeng.shengyapo.model.BikeInfo;
import com.ruipeng.shengyapo.service.CouponService;
import com.ruipeng.shengyapo.service.OrderService;
import com.ruipeng.shengyapo.service.UserService;
import com.ruipeng.shengyapo.utils.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.SocketChannel;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruipeng.shengyapo.dao.BikeMapper;
import com.ruipeng.shengyapo.service.BikeService;

@Service
public class BikeServiceImpl implements BikeService {

    @Autowired
    private BikeMapper bikeMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CouponMapper couponMapper;

    @Override
    public List<Map<String, Object>> getBikesAround(Map<String, Object> params) {
        System.out.println(params.toString());
        return bikeMapper.getBikesAround(params);
    }

    @Override
    public Map<String, Object> getLockIMEIByBikeNo(Map<String, Object> params) {
        return bikeMapper.getLockIMEIByBikeNo(params);
    }

    @Override
    public int saveBikeRepair(Map<String, Object> params) {
        return bikeMapper.saveBikeRepair(params);
    }

    @Override
    public ResponseData openBike(Map<String, Object> params, ResponseData data) {
        int userId = Integer.parseInt(params.get("userId").toString());
        Map<String, Object> bikeMap = bikeMapper.getLockIMEIByBikeNo(params);
        if (bikeMap == null) {
            //车辆编号错误
            data.setMsg("车辆编号错误");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        }
        String lockState = (String) bikeMap.get("lockState");
        if (lockState.equals("1")) {
            //余额不足
            data.setMsg("车辆已使用");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        }
        //用户对象
        Map<String, Object> userInfo = userService.getByUserId(userId);
        //用户余额
        double money = Double.parseDouble(userInfo.get("userAccount").toString());

        if (money < 0) {
            //余额不足
            data.setMsg("余额不足");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        }

        //用户是否交押金
        double isDeposit = Double.parseDouble(userInfo.get("deposit").toString());

        if (isDeposit == 0) {
            //未交押金
            data.setMsg("未交押金");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        }

        //是否有未完成的订单
        params.put("userId", userId);
        List<Map<String, Object>> orderList = orderService.getUserOrderByUserId(params);
        if (orderList.size() > 0) {
            //您有未完成的订单，
            data.setMsg("您有未完成的订单");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        } else {
            try {
                //开锁  根据车辆编号找到对于的imeiId
                String imei = (String) bikeMap.get("lockIMEI");
                SocketChannel sch = (SocketChannel) NettyChannelMap.get(imei);
                System.out.println("sch=" + sch);
                if (sch != null) {
                    //修改车辆状态
                    //params.put("lockState", "1");
                    //bikeMapper.updateBikeStatusByBikeId(params);

                    //开锁成功
                    //System.out.println("send order: " + LockManager.getOpenLockCmd(imei));
                    ByteBuf resp = Unpooled.copiedBuffer(LockManager.getOpenLockCmd(imei));
                    sch.writeAndFlush(resp);//发送开锁指令
                    //System.out.println("发送开锁指令完毕！");

                    //一分钟循环12次
                    for (int i = 0; i < 6; i++) {

                        params.put("imei", imei);

                        String reslut = HttpUtils.sendPost("http://localhost:80/sypappservice/bike/info?bikeId="+params.get("bikeNo"),"");

                        JSONObject bikeJson = JSONObject.fromObject(reslut);
                        lockState = bikeJson.getString("lockState");

                        System.out.println("count = " + i);
                        if (lockState.equals("0")) {
                            data.setState(ContentUtils.COMM_STATE_FALSE);
                            data.setMsg("共享单车未连接到服务器");
                        } else {
                            //生成用户行踪订单
                            //增加自行车id
                            params.put("bikeId", bikeMap.get("bikeId"));
                            Map<String, Object> orderInfo = getUserTidingOrderNo(params);

                            data.setState(ContentUtils.COMM_STATE_TRUE);
                            data.setResults(orderInfo);
                            break ;
                        }

                        //停止5秒
                        Thread.sleep(5000);
                    }

                } else {
                    data.setState(ContentUtils.COMM_STATE_FALSE);
                    data.setMsg("开锁失败");
                    return data;
                }
                System.out.println("===================== ");
                System.out.println("===================== ");
                System.out.println("  response =  " + JSONObject.fromObject(data));
                System.out.println("===================== ");
                System.out.println("===================== ");
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                //发现两辆可开启的车
                data.setMsg("发现多辆可开启的车");
                data.setState(ContentUtils.COMM_STATE_FALSE);
                return data;
            }
        }
    }

    @Override
    public int updateCloseBikeByOrderNo(Map<String, Object> params) {
        // 获取最近订单
        Map<String, Object> orderData = orderMapper.getBikeOrderByBikeNo(params);
        if (orderData != null) {
            System.out.println("orderData: " + orderData);
            Integer riding_status = (Integer) orderData.get("riding_status");
            if (riding_status == 0) { // 订单未完成
                Date endTime = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                Date startDate = null;
                try {
                    startDate = format.parse((String) orderData.get("order_createtime"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                System.out.println("endTime: " + endTime.getTime() + "  createTime: " + startDate.getTime());
                System.out.println("deltaTime: " + (endTime.getTime() - startDate.getTime()));
                double riding_time = (endTime.getTime() - startDate.getTime()) / 1000; // 骑行时常（秒）
                System.out.println("ridingTime: " + riding_time);
                long riding_unit = (long) Math.ceil((double) riding_time / 60 / 30); // 多少个30分钟
                System.out.println("riding_unit: " + riding_unit);
                double riding_cost = 0.5 * riding_unit; // 骑行费用（元）
                riding_cost = riding_cost > 24 ? 24 : riding_cost; // 最多2元
                System.out.println("riding_cost: " + riding_cost);

                // 构建订单对象
                Map<String, Object> orderParams = new HashMap<String, Object>();
                // 用户id
                Integer userId = (Integer) orderData.get("user_id");
                //获取优惠券列表
                List<Map<String, Object>> couponList = couponMapper.getCouponListByUserId(userId);
                double couponMoney = 0;
                if (couponList.size() > 0) {
                    //使用优惠券，
                    orderParams.put("coupon_no", couponList.get(0).get("couponNo"));
                    //更改优惠券状态
                    System.out.println("couponNo = " + couponList.get(0).get("couponNo").toString());
                    couponMapper.updateCouponByCouponNo(couponList.get(0).get("couponNo").toString());
                    //获取优惠券金额
                    couponMoney = Double.parseDouble(couponList.get(0).get("couponMoney").toString());
                    //当本次骑行订单金额大于优惠券金额
                    if (riding_cost <= couponMoney) {

                        riding_cost = 0;

                    } else {
                        riding_cost = riding_cost - couponMoney;

                        // 查询用户余额
                        Map<String, Object> userSearchParams = new HashMap<String, Object>();
                        userSearchParams.put("user_id", userId);
                        Map<String, Object> accountData = userMapper.getUserAccount(userSearchParams);

                        // 扣除用户余额
                        BigDecimal account = (BigDecimal) accountData.get("user_account");
                        BigDecimal result = account.subtract(new BigDecimal(riding_cost));
                        Map<String, Object> userAccountParams = new HashMap<String, Object>();
                        userAccountParams.put("userId", userId);
                        userAccountParams.put("user_account", result.doubleValue());
                        userMapper.setUserAccount(userAccountParams);
                    }
                } else {
                    // 查询用户余额
                    Map<String, Object> userSearchParams = new HashMap<String, Object>();
                    userSearchParams.put("user_id", userId);
                    Map<String, Object> accountData = userMapper.getUserAccount(userSearchParams);

                    // 扣除用户余额
                    BigDecimal account = (BigDecimal) accountData.get("user_account");
                    BigDecimal result = account.subtract(new BigDecimal(riding_cost));
                    Map<String, Object> userAccountParams = new HashMap<String, Object>();

                    System.out.println("result.doubleValue()=" + result.doubleValue());

                    userAccountParams.put("userId", userId);
                    userAccountParams.put("user_account", result.doubleValue());
                    userMapper.setUserAccount(userAccountParams);
                }
                // 更新订单
                orderParams.put("order_endtime", endTime);
                orderParams.put("riding_time", riding_time);
                orderParams.put("riding_cost", riding_cost);
                // carbon_saving, consume_kcal, riding_status 等
                orderParams.put("riding_order_id", orderData.get("riding_order_id"));
                orderMapper.completeOrder(orderParams);
                return 1;
            }
        } else {
            return 0;
        }
        return 0;
    }

    @Override
    public int insertBikeInfoBatch(List<?> bikeList) {
        return bikeMapper.insertBikeInfoBatch(bikeList);
    }

    public Map<String, Object> getUserTidingOrderNo(Map<String, Object> params) {
        String orderNo = ObjUtils.getNowDate() + ObjUtils.randomNumeric(4) + "00100" + ObjUtils.randomNumeric(6) + "00" + ObjUtils.randomNumeric(4);
        params.put("orderNo", orderNo);
        int count = orderService.initAddRiDingOrder(params);
        params.put("count", count);
        return params;
    }
}


